package com.example.hzzrpc.config.registrycenter;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：hzz
 * @description：TODO
 * @date ：2022/1/2 11:43
 */
public class RpcServerContext implements ApplicationContextAware {

    private String keyName = "rpcserver:";

    private Environment environment;

    private ApplicationContext applicationContext;


    /**
     * 实际执行bean的方法
     * @return
     */
    public Object doExecutionMethod(String serverName,String metherName){
        if (rpcServerMap.containsKey(serverName)) {
            Object bean = applicationContext.getBean(String.valueOf(rpcServerMap.get(serverName)));
            try {
                Method declaredMethod = bean.getClass().getDeclaredMethod(metherName);
                Object o = ReflectionUtils.invokeMethod(declaredMethod, bean);
                return o;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;

    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String NettyIp="127.0.0.1";
    private int port = 9999;

    private ConcurrentHashMap rpcServerMap = new ConcurrentHashMap();

    public void addRpcServer(String ServerName, String beanName) {

        rpcServerMap.put(ServerName, beanName);

        stringRedisTemplate.opsForValue().set(keyName + ServerName,NettyIp+":"+port);
    }

    public String getNettyIp() {
        return NettyIp;
    }

    public int getPort() {
        return port;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
